<script setup>
import { computed, onMounted, onUnmounted } from 'vue'
import AppHeader from './components/AppHeader.vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 不显示头部导航的页面列表
const hideHeaderPages = ['/', '/auth/dingtalk/callback', '/register']

// 检查当前页面是否应该隐藏头部
const shouldHideHeader = computed(() => {
  return hideHeaderPages.includes(route.path)
})

// 检查用户是否已登录
function isAuthenticated() {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  return !!token
}

// 处理浏览器返回按钮
function handlePopState(event) {
  const isLoggedIn = isAuthenticated()
  const currentPath = route.path
  
  console.log('浏览器导航事件:', { currentPath, isLoggedIn })
  
  // 如果用户已登录但试图返回到登录/注册页面
  if (isLoggedIn && (currentPath === '/' || currentPath === '/register')) {
    console.log('阻止已登录用户返回到登录页面')
    event.preventDefault()
    router.replace('/home')
    return
  }
  
  // 如果用户未登录但试图访问需要认证的页面
  if (!isLoggedIn && route.meta?.requiresAuth) {
    console.log('阻止未登录用户访问认证页面')
    event.preventDefault()
    router.replace('/')
    return
  }
}

onMounted(() => {
  // 监听浏览器的前进/后退按钮
  window.addEventListener('popstate', handlePopState)
  
  // 在页面加载时添加一个状态，防止意外的浏览器导航
  if (window.history.state === null) {
    window.history.replaceState({ navigationGuard: true }, '', window.location.href)
  }
})

onUnmounted(() => {
  window.removeEventListener('popstate', handlePopState)
})
</script>

<template>
  <AppHeader v-if="!shouldHideHeader" />
  <router-view></router-view>
</template>

<style scoped>

</style>